import { Module } from '@nestjs/common'
import { MulterModule } from '@nestjs/platform-express'
import { ConfigModule, ConfigService } from '@nestjs/config'
import { UploadController } from './upload.controller'
import { UploadService } from './upload.service'
import { DatabaseModule } from '../database/database.module'
import { memoryStorage } from 'multer'

/**
 * 文件上传模块
 * 配置文件上传功能，包括Multer配置和相关服务
 */
@Module({
  imports: [
    DatabaseModule,
    ConfigModule,
    MulterModule.registerAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        storage: memoryStorage(), // 使用内存存储，由服务处理文件保存
        limits: {
          fileSize: configService.get<number>('UPLOAD_MAX_SIZE', 10 * 1024 * 1024), // 默认10MB
          files: 10 // 最多10个文件
        },
        fileFilter: (req, file, callback) => {
          // 基础文件类型检查
          const allowedMimeTypes = [
            // 图片
            'image/jpeg',
            'image/png',
            'image/gif',
            'image/webp',
            'image/svg+xml',
            // 文档
            'application/pdf',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'application/vnd.ms-excel',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'application/vnd.ms-powerpoint',
            'application/vnd.openxmlformats-officedocument.presentationml.presentation',
            'text/plain',
            'text/csv',
            // 音频
            'audio/mpeg',
            'audio/wav',
            'audio/ogg',
            'audio/mp4',
            // 视频
            'video/mp4',
            'video/mpeg',
            'video/quicktime',
            'video/x-msvideo',
            'video/webm',
            // 压缩文件
            'application/zip',
            'application/x-rar-compressed',
            'application/x-7z-compressed',
            // 其他
            'application/json',
            'application/xml'
          ]

          if (allowedMimeTypes.includes(file.mimetype)) {
            callback(null, true)
          } else {
            callback(new Error(`不支持的文件类型: ${file.mimetype}。支持的类型: ${allowedMimeTypes.join(', ')}`), false)
          }
        }
      }),
      inject: [ConfigService]
    })
  ],
  controllers: [UploadController],
  providers: [UploadService],
  exports: [UploadService]
})
export class UploadModule {}
